package lastSymbol

import (
	"log"
	"strconv"
	"time"

	"github.com/Jeffail/gabs"
	kjson "github.com/heyuanlong/go-tools/json"
	"github.com/parnurzeal/gorequest"
)

type AofexPrice struct {
	httpDomain string
}

func NewAofexPriceStruct() *AofexPrice {
	obj := &AofexPrice{}
	obj.init()
	return obj
}

func (ts *AofexPrice) init() {
	ts.httpDomain = "https://openapi.aofex.com"
}

func (ts *AofexPrice) GetPriceUsdt(name string) (float64, error) {
	symbol := name + "-USDT"
	return ts.GetPrice(symbol)
}

func (ts *AofexPrice) GetPriceRmb(name string) (float64, error) {
	symbol := name + "-AQ"
	return ts.GetPrice(symbol)
}

func (ts *AofexPrice) GetPrice(symbol string) (float64, error) {
	uri := ts.httpDomain + "/openApi/market/trade?symbol=" + symbol

	request := gorequest.New().Timeout(time.Duration(2) * time.Second)
	_, body, errs := request.Get(uri).End()
	if errs != nil {
		log.Println(errs)
		return 0, errs[0]
	}

	jsonParsed, err := gabs.ParseJSON([]byte(body))
	if err != nil {
		log.Println(body, err)
		return 0, err
	}

	containers, err := jsonParsed.Path("result.data").Children()
	if err != nil || len(containers) == 0 {
		log.Println(body, err)
		return 0, err
	}
	s, err := kjson.GabsGetJsonString(containers[0], "price")
	if err != nil {
		log.Println(body, err)
		return 0, err
	}

	retv, errx := strconv.ParseFloat(s, 64)
	return retv, errx
}
